<?php

/**
 * 日志类
 */

namespace variant\core;

class Logger {

    /**
     * 是否可写
     * @var array
     */
    protected $writeAble = false;

    /**
     * 实例化日志类
     */
    public function __construct() {
        $this->writeAble = Config::get('EXCEPTIONS.LOG_ON');
    }

    /**
     * 致命错误
     */
    public function fatal($string) {
        $this->write($string, 'FATAL');
    }

    /**
     * 一般错误
     */
    public function error($string) {
        $this->write($string, 'ERROR');
    }

    /**
     * 应用警告
     */
    public function warn($string) {
        $this->write($string, 'WARN');
    }

    /**
     * 基本信息
     */
    public function info($string) {
        if ($this->level & Logger::INFO) {
            $this->write($string, 'INFO');
        }
    }

    /**
     * Debug
     */
    public function debug($string) {
        $this->write($string, 'DEBUG');
    }

    /**
     * Trace
     */
    public function trace($string) {
        $this->write($string, 'TRACE');
    }



    //执行写日志
    protected function write($string, $levelName = '') {
        if(!$this->writeAble){
            return;
        }
        $logDir = DATA_PATH . 'log/';
        if(!is_dir($logDir)){
            if(!@mkdir($logDir, 0777, true)){
                throw new \Exception('Unable to create "' . $logDir . '"', 500);
            }
        }
        $logFile = $logDir . date('Ymd') . '.log';
        $time = date('Y-m-d H:i:s');

        $storage = new Storage('file');
        $storage->append($logFile, "[$levelName] [$time] [$string] \n");
    }

}